package org.example.item.wallet;

import org.example.models.interfaces.Action;
import org.example.person.Person;

import java.util.Optional;

public class WalletActions {

    private static Optional<Wallet> getWallet(Person person) {
        return person.getOwnables().stream()
                .filter(Wallet.class::isInstance)
                .findAny()
                .map(Wallet.class::cast);
    }

    public static Action<Person> transferMoney(Person to, int amount) {
        return person -> {
            Wallet fromWallet = getWallet(person).orElseThrow(() -> new WalletException("User doesn't have a wallet"));
            Wallet toWallet = getWallet(to).orElseThrow(() -> new WalletException("User doesn't have a wallet"));
            try {
                fromWallet.setBalance(fromWallet.getBalance() - amount);
                toWallet.setBalance(toWallet.getBalance() + amount);
            } catch (IllegalArgumentException e) {
                throw new WalletException("User has sufficient balance for transfer");
            }

        };
    }
}
